package com.shijiu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.shijiu.common.paramCommon;
import com.shijiu.service.MsmService;
import com.shijiu.utils.ConstantPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xlj
 * @Date Created in  2023/2/23 17:25
 * @DESCRIPTION:
 * @Version V1.0
 */
@Service
@SuppressWarnings("all")
@Slf4j
public class MsmServiceImpl implements MsmService {
    private static final String CODE="code";

    //根据手机号，存入验证码
    @Override
    public Boolean send(String phoneNum, String code) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phoneNum)) {
            return false;
        }
        //整合阿里云的短信服务
        DefaultProfile profile = DefaultProfile.
                getProfile(ConstantPropertiesUtils.REGION_Id,
                        ConstantPropertiesUtils.ACCESS_KEY_ID,
                        ConstantPropertiesUtils.SECRECT);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(paramCommon.DYSMSAPI_ALIYUNCS_COM);
        request.setVersion(paramCommon.DATA_VERSION);
        request.setAction(paramCommon.SET_ACTION);
        //手机号
        request.putQueryParameter(paramCommon.PHONE_NUMBERS, phoneNum);
        //签名名称
        request.putQueryParameter(paramCommon.SIGN_NAME, paramCommon.PARAM_VALUE);
        //模板code
        request.putQueryParameter(paramCommon.TEMPLATE_CODE, paramCommon.TEMPLATE_VALUE);
        //验证码  使用json格式   {"code":"123456"}
        Map<String,Object> param = new HashMap();
        param.put(CODE,code);
        request.putQueryParameter(paramCommon.TEMPLATE_PARAM, JSONObject.toJSONString(param));
        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            System.out.println(response.getHttpStatus());
            System.out.println(response.getHttpResponse());
            log.info("当前发送短信的结果为:{}",response.getData().toString());
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
